<template>
  <div class="app-toolbox-xmap-center" v-show="me.state.enabled.show">
    <iframe :id="`kity-${this.me.state.mid}`" class="app-toolbox-xmap-center__kity" :src="target" ref="kity" @auto-synchronize="handleAutoSynchronize" @force-synchronize="handleForceSynchronize" @enable-editor="handleEditorAvaiable"></iframe>
  </div>
</template>

<script>
  export default {
    name: 'app-toolbox-xmap-center',
    props: {
      store: {
        type: Object,
        required: true,
      },
      me: {
        type: Object,
        required: true,
      },
    },
    computed: {
      meId() {
        return this.me.state.mid;
      },
      meCanInserted() {
        return this.me.state.enabled.insert;
      },
      meCanLoad() {
        if (this.meId === this.currentId && this.meCanInserted && !this.me.state.init) {
          return true;
        }
        return false;
      },
      currentId() {
        return this.store.current.mid;
      },
      synchronize() {
        return this.me.state.synchronize;
      },
      meName() {
        return this.me.name;
      },
      meSynopsis() {
        return this.me.synopsis;
      },
    },
    data() {
      return {
        target: '',
      };
    },
    created() {
      if (process.env.NODE_ENV === 'development') {
        this.target = `/static/kity/index.html?mid=${this.me.state.mid}`;
      } else {
        this.target = `https://www.todaytomato.com/static/kity/index.html?mid=${this.me.state.mid}`;
      }
    },
    watch: {
      meName() {
        this.updateItem();
      },
      currentId(mid, oldid) {
        if (mid === this.me.state.mid) {
          this.me.state.enabled.show = true;
        }
        if (oldid === this.me.state.mid) {
          this.me.state.enabled.show = false;
          this.me.state.synchronize = 'force-todo';
        }
      },
      meCanLoad(val) {
        if (val) {
          this.query();
          this.me.state.init = true;
        }
      },
      synchronize(sync) {
        if (this.me.state.enabled.update && sync === 'force-todo') {
          this.update();
        }
        if (this.me.state.enabled.update && sync === 'todo') {
          window.setTimeout(() => {
            this.update();
          }, 20000);
        }
      },
    },
    destroyed() {
      this.me.state.enabled.show = false;
      this.me.state.enabled.update = false;
      this.me.state.enabled.insert = false;
    },
    methods: {
      handleEditorAvaiable() {
        this.me.state.enabled.insert = true;
      },
      handleForceSynchronize() {
        this.me.state.synchronize = 'force-todo';
      },
      handleAutoSynchronize() {
        this.$parent.$emit('editing');
        if (this.me.state.synchronize === 'todo') {
          return;
        }
        this.me.state.synchronize = 'todo';
      },
      getQueryTargetUrl() {
        if (this.me.state.type === 'topic') {
          return `api/topics/${this.me.id}/xmapContent`;
        }
        if (this.me.state.type === 'module') {
          return `api/modules/${this.me.id}/xmapContent`;
        }
        return null;
      },
      getUpdateTargetUrl() {
        if (this.me.state.type === 'topic') {
          return `api/topics/${this.me.id}`;
        }
        if (this.me.state.type === 'module') {
          return `api/modules/${this.me.id}`;
        }
        return null;
      },
      query() {
        this.store.loadingDialog.visible = true;
        const url = this.getQueryTargetUrl();
        this.me.state.synchronize = 'doing';
        this.$http.request({
          url,
          method: 'get',
        }).then((response) => {
          this.me.xmapContent = response.data;
          this.me.state.synchronize = 'success';
          /* 避免导图与名称不同步 */
          if (this.me.name !== this.me.xmapContent.root.data.text) {
            this.me.xmapContent.root.data.text = this.me.name;
          }
          if (this.me.state.enabled.insert === true) {
            this.$refs.kity.contentWindow.editor.minder.importJson(this.me.xmapContent);
            this.me.state.enabled.update = true;
            if (this.store.current.mid === this.me.state.mid) {
              this.me.state.enabled.show = true;
            }
          }
          this.store.loadingDialog.visible = false;
        }).catch(() => {
          this.me.state.synchronize = 'failure';
        });
      },
      updateItem() {
        if (this.me.state.enabled.update) {
          this.me.xmapContent.root.data.text = this.me.name;
          this.$refs.kity.contentWindow.editor.minder.importJson(this.me.xmapContent);
        }
      },
      update() {
        if (this.me.state.enabled.update) {
          this.me.xmapContent = this.$refs.kity.contentWindow.editor.minder.exportJson();
          this.me.name = this.me.xmapContent.root.data.text;
          const name = this.me.name;
          const synopsis = this.me.synopsis;
          const xmapContent = JSON.stringify(this.me.xmapContent);
          const url = this.getUpdateTargetUrl();
          this.me.state.synchronize = 'doing';
          this.$http.request({
            url,
            method: 'put',
            data: {
              name,
              synopsis,
              xmapContent,
            },
            transformRequest: [(data) => {
              const encodeName = encodeURIComponent(data.name);
              const encodeSynopsis = encodeURIComponent(data.synopsis);
              const encodeXmapContent = encodeURIComponent(data.xmapContent);
              return `name=${encodeName}&synopsis=${encodeSynopsis}&xmapContent=${encodeXmapContent}`;
            }],
          }).then(() => {
            this.me.state.synchronize = 'success';
          }).catch(() => {
            this.me.state.synchronize = 'failure';
          });
        }
      },
    },
  };
</script>